from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os

# 生成密钥
key = os.urandom(16)  # 16 字节密钥 (AES-128)
cipher = AES.new(key, AES.MODE_CBC)  # 使用 CBC 模式

# 明文
data = b'This is a secret message.'

# 填充明文并进行加密
padded_data = pad(data, AES.block_size)
iv = cipher.iv  # 初始化向量
ciphertext = cipher.encrypt(padded_data)

# 输出结果
print(f'Key: {key.hex()}')
print(f'IV: {iv.hex()}')
print(f'Ciphertext: {ciphertext.hex()}')

# 解密
cipher_decrypt = AES.new(key, AES.MODE_CBC, iv)
decrypted_data = unpad(cipher_decrypt.decrypt(ciphertext), AES.block_size)

# 输出解密后的明文
print(f'Decrypted: {decrypted_data.decode()}')